<template>
  <view style="width: 100%">
    <view>
      <scroll-view :scroll-x="true" class="scrollview-box">
        <view style="margin: 10px auto; width: 200px; color: #999"
          >请选择要融合的模版图片</view
        >
        <up-tabs :list="listTag" @click="fetchList"></up-tabs>
        <block v-for="item in list" :key="item">
          <view style="width: 100px; height: 120px" class="item">
            <up-image
              height="100"
              width="100"
              @click="handleChose(item)"
              mode="aspectFit"
              :src="item.thumb"
            ></up-image>
            <view v-show="item.checked"> {{ "√" }} </view>
          </view>
        </block>
      </scroll-view>
    </view>

    <view>
      <up-empty
        v-if="!chooseFileUrl"
        style="
          border: 1px solid #999;
          margin: 10px auto;
          height: 50%;
          width: 50%;
        "
        text="请选择要上传的本地图片"
        icon="http://cdn.uviewui.com/uview/empty/car.png"
      >
      </up-empty>
      <view v-else style="display: flex"
        ><up-image
          height="200"
          width="200"
          mode="aspectFit"
          :src="chooseFileUrl"
        ></up-image>
        <up-empty
          v-if="!isMixed"
          style="
            border: 1px solid #999;
            margin: 10px auto;
            height: 200px;
            width: 200px;
          "
          text="请点击下方确定融合按钮"
          icon="http://cdn.uviewui.com/uview/empty/car.png"
        />
        <up-image
          v-else
          previewFullImage
          height="200"
          width="200"
          mode="aspectFit"
          :src="mixedUrl"
        ></up-image>
      </view>

      <up-button
        style="width: 50%"
        @click="chooseFile"
        type="primary"
        text="选择图片"
      ></up-button>
    </view>
  </view>
  <button style="width: 50%; margin-top: 20px" @click="handleMix">
    确定融合
  </button>
</template>

<script setup>
import { reactive, ref, onMounted} from "vue";
import request from "@/utils/request";
const FACE_KEY = "PVTKkiQlknBYZ0YIaIxLtm3j7b8a3qW5";
const FACE_SECRET = "y-TcTKtatl96SCsidpT5aXCdxYQHeBox";
const mixParams = reactive({
  api_key: FACE_KEY,
  api_secret: FACE_SECRET,
  template_url: null,
  merge_file: null,
});

const listTag = ref([]);
const list = ref([]);

const fetchList = async (item) => {
  const id = item.id; // 获取当前标签的id
  try {
    const response = await http.request({
      method: "GET",
      url: `/prod/pageProd?categoryId=${id}`,
    });
    if (response.data && response.data.records && Array.isArray(response.data.records)) {
      // 假设响应的数据包含一个名为 pic 的数组，其中包含图片信息
      list.value = response.data.records.map(record => ({
        thumb: record.pic, // 使用pic字段作为图片URL
        checked: false,
      }));
      console.log(list.value);
    } else {
      console.error("无效的响应格式");
    }
  } catch (error) {
    console.error("获取列表数据时出错:", error);
  }
};

onMounted(async () => {
  try {
    const response = await http.request({
      method: "GET",
      url: `/category/categoryInfo?parentId=${0}`, // 更新为实际的接口地址
    });
    if (response.data && Array.isArray(response.data)) {
      listTag.value = response.data.map(item => ({name: item.categoryName, id: item.categoryId}));
      console.log(listTag.value)
      if (listTag.value.length > 0) {
        fetchList(listTag.value[0]);
      }
    } else {
      console.error("无效的响应格式");
    }
  } catch (error) {
    console.error("获取 listTag 时出错:", error);
  }
});
const tFile = ref(null);
// 本地选择的图片临时生成的url
const chooseFileUrl = ref("");
const isMixed = ref(false);
const chooseFile = async () => {
  uni.chooseFile({
    success: (res) => {
      tFile.value = res.tempFiles.map((item) => item);
      const file = tFile.value[0];
      chooseFileUrl.value = URL.createObjectURL(file);
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onload = (event) => {
        // 拿到需要上传的图片的二进制文件
        mixParams.merge_file = event.target.result;
      };
    },
    fail: (err) => {
      console.error("选择文件失败：", err);
    },
  });
};

// 选择模版图片
const handleChose = async (item) => {
  list.value.forEach((listItem) => {
    if (listItem.checked) {
      listItem.checked = false;
    }
  });
  mixParams.template_url = item.thumb;
  item.checked = !item.checked;
};

const mixedUrl = ref("");
// 融合按钮
const handleMix = async () => {
  try {
    const res = await request({
      url: "",
      method: "POST",
      data: mixParams,
    });
    isMixed.value = true;
    // mixedUrl.value = res.result
    // const curFile = base64ToFile(res.result)
    mixedUrl.value = base64ToURL2(res.result,'image/jpeg');
    console.log(mixedUrl.value,curFile);
  } catch (err) {
    console.log(err);
  }
};

const base64ToURL2 = (base64String, fileType) => {
  // fileType 是你要处理的文件类型，比如 'application/pdf'、'image/png' 等
  // 直接将 Base64 字符串嵌入到 URL 中
  const url = `data:${fileType};base64,${base64String}`;
  return url;
}
</script>

<style scoped lang="scss">
.scrollview-box {
  white-space: nowrap;
  /* 滚动必须加的属性 */
  width: 100%;
  padding: 20rpx 20rpx 20rpx 20rpx;
}
.item {
  margin-right: 20rpx;
  display: inline-flex;
  /* item的外层定义成行内元素才可进行滚动 inline-block / inline-flex 均可 */
  flex-direction: column;
  align-items: center;
}

.cover {
  width: 165rpx;
  height: 165rpx;
}
</style>
